import 'package:flutter/material.dart';
import 'package:flutter_rfid_dmo/model/tag.dart';

class RfidDashboardPage extends StatefulWidget {
  const RfidDashboardPage({super.key});

  @override
  State<RfidDashboardPage> createState() => _RfidDashboardPageState();
}

class _RfidDashboardPageState extends State<RfidDashboardPage> {
  // 示例数据
  String deviceName = "RFD4030";
  int batteryLevel = 80;
  int uniqueTags = 7;
  int totalReads = 89;
  String memoryBank = "None";
  List<Map<String, dynamic>> tagList = [
    {"tag": "EE00000000000000000000311", "count": 20, "rssi": -58},
    {"tag": "E28011700000020D2A412321", "count": 12, "rssi": -69},
  ];

  String generatePlugEpc({
    required int fiberNo,
    required int type, // 1=SC, 2=FC
  }) {
    final fiberStr = fiberNo.toString().padLeft(4, '0');
    final typeStr = type.toHex();
    // 校验码可自定义算法，这里简单示例
    final checkCode = ((fiberNo + type) % 256)
        .toRadixString(16)
        .padLeft(2, '0')
        .toUpperCase();
    return '$fiberStr$typeStr$checkCode';
  }

  String generatePortEpc({
    required int odfNo,
    required int trayNo,
    required int portNo,
  }) {
    // ODF编号4位，托盘号4位，端口号4位
    final odfStr = odfNo.toString().padLeft(4, '0');
    final trayStr = trayNo.toString().padLeft(4, '0');
    final portStr = portNo.toString().padLeft(4, '0');
    return '$odfStr$trayStr$portStr';
  }

  void _showWritePortDialog() {
    final _formKey = GlobalKey<FormState>();
    final odfController = TextEditingController(text: '1');
    final trayController = TextEditingController(text: '1');
    final portController = TextEditingController(text: '1');

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('写入端口标签'),
          content: Form(
            key: _formKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextFormField(
                  controller: odfController,
                  decoration: const InputDecoration(labelText: 'ODF编号（1-3）'),
                  keyboardType: TextInputType.number,
                  validator: (value) {
                    final v = int.tryParse(value ?? '');
                    if (v == null) return '请输入数字';
                    if (v < 1 || v > 3) return '范围1-3';
                    return null;
                  },
                ),
                TextFormField(
                  controller: trayController,
                  decoration: const InputDecoration(labelText: '托盘号（1-6）'),
                  keyboardType: TextInputType.number,
                  validator: (value) {
                    final v = int.tryParse(value ?? '');
                    if (v == null) return '请输入数字';
                    if (v < 1 || v > 6) return '范围1-6';
                    return null;
                  },
                ),
                TextFormField(
                  controller: portController,
                  decoration: const InputDecoration(labelText: '端口号（1-12）'),
                  keyboardType: TextInputType.number,
                  validator: (value) {
                    final v = int.tryParse(value ?? '');
                    if (v == null) return '请输入数字';
                    if (v < 1 || v > 12) return '范围1-12';
                    return null;
                  },
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                if (_formKey.currentState?.validate() ?? false) {
                  final odf = int.parse(odfController.text);
                  final tray = int.parse(trayController.text);
                  final port = int.parse(portController.text);
                  final epc =
                      generatePortEpc(odfNo: odf, trayNo: tray, portNo: port);
                  // TODO: 调用RFID写入方法
                  Navigator.pop(context);
                  ScaffoldMessenger.of(context)
                      .showSnackBar(SnackBar(content: Text('EPC: $epc')));
                }
              },
              child: const Text('写入'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(deviceName, overflow: TextOverflow.ellipsis),
        actions: [
          const Icon(Icons.battery_full, color: Colors.green),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text("$batteryLevel%")),
          ),
        ],
      ),
      body: Column(
        children: [
          // 统计区
          Container(
            color: Colors.grey[200],
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _statItem("MEMORY BANK", memoryBank),
                _statItem("UNIQUE TAGS", uniqueTags.toString()),
                _statItem("TOTAL READS", totalReads.toString()),
              ],
            ),
          ),
          // 搜索栏
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              decoration: InputDecoration(
                prefixIcon: const Icon(Icons.search),
                hintText: "搜索标签",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                isDense: true,
              ),
              onChanged: (value) {
                // TODO: 搜索逻辑
              },
            ),
          ),
          // 列表头
          Container(
            color: Colors.grey[100],
            padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16),
            child: const Row(
              children: [
                Expanded(
                    flex: 5,
                    child: Text("TAG",
                        style: TextStyle(fontWeight: FontWeight.bold))),
                Expanded(
                    flex: 2,
                    child: Text("Count",
                        textAlign: TextAlign.center,
                        style: TextStyle(fontWeight: FontWeight.bold))),
                Expanded(
                    flex: 2,
                    child: Text("RSSI",
                        textAlign: TextAlign.center,
                        style: TextStyle(fontWeight: FontWeight.bold))),
              ],
            ),
          ),
          // 标签列表
          Expanded(
            child: ListView.builder(
              itemCount: tagList.length,
              itemBuilder: (context, index) {
                final tag = tagList[index];
                return ListTile(
                  title: Text(tag["tag"]),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                          width: 40,
                          child: Text("${tag["count"]}",
                              textAlign: TextAlign.center)),
                      SizedBox(
                          width: 40,
                          child: Text("${tag["rssi"]}",
                              textAlign: TextAlign.center)),
                    ],
                  ),
                );
              },
            ),
          ),
        ],
      ),
      // 底部操作按钮
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.only(bottom: 16.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            FloatingActionButton.extended(
              heroTag: "scan",
              onPressed: () {
                // TODO: 盘点/停止盘点
              },
              icon: const Icon(Icons.play_arrow),
              label: const Text("盘点"),
              backgroundColor: Colors.blue,
            ),
            FloatingActionButton.extended(
              heroTag: "write",
              onPressed: () {
                _showWritePortDialog(); // 调用写入弹窗
              },
              icon: const Icon(Icons.edit),
              label: const Text("写入"),
              backgroundColor: Colors.green,
            ),
            FloatingActionButton.extended(
              heroTag: "read",
              onPressed: () {
                // TODO: 读取标签
              },
              icon: const Icon(Icons.qr_code_scanner),
              label: const Text("读取"),
              backgroundColor: Colors.orange,
            ),
          ],
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }

  Widget _statItem(String label, String value) {
    return Column(
      children: [
        Text(label, style: TextStyle(fontSize: 12, color: Colors.grey[600])),
        const SizedBox(height: 2),
        Text(value,
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
      ],
    );
  }
}
